<?php
/**
 * 拍卖模型
 */

namespace app\admin\model;


use app\admin\model\House as HouseModel;
use app\common\lib\RespCode;
use app\common\model\BaseModel;
use custom\Err;
use house\HouseCount2;
use PDOStatement;
use think\Collection;
use think\Db;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\exception\DbException;
use think\Model;

class HouseAuction extends BaseModel {

    const ASTATUS = [1, 2, 3, 4, 5, 6, 7];
    const ATYPE = [1, 2, 3, 4, 5];

    /**
     * 获取拍卖纪录
     * @param $house_id
     * @return array|PDOStatement|string|Collection
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    public static function getHistory($house_id) {
        $column = ['type,start_time,end_time,auction_status,market_price,consult_price,price_lower_offset,court_name,contact_name,contact_tel,source_id,source_type,enroll_num,access_num,remind_num,source_url,id as history_id,bond,final_price,bid_count,IF(type=4,pay_selloff,initial_price) as initial_price,tail_money_date'];
        //房源对应的所有拍卖id
        $ids = self::where('house_id', $house_id)->order('id desc')->column('id');
        if ($ids) {
            $id_arr_str = join(',', $ids);
            $data = self::getDatas([['house_id', '=', $house_id]], $column, [], $id_arr_str);
            foreach ($data as $k => $v) {
                $data[$k]['typename'] = House::A_TYPES[$v['type']];
                // 待开始/进行中/成交 才有保证金
                if (in_array($data[$k]['auction_status'], [1, 2, 3])) {
                    $data[$k]['bond'] = deal_data_info($data[$k]['bond'], 2);
                } else {
                    unset($data[$k]['bond']);
                }
                //成交
                if ($data[$k]['auction_status'] == 3) {
                    $data[$k]['final_price'] = deal_data_info($data[$k]['final_price'], 2);
                } else {
                    unset($data[$k]['final_price']);
                    unset($data[$k]['bid_count']);
                }
                $data[$k]['auction_status'] = House::A_STATUSS[$v['auction_status']];

                $data[$k]['initial_price'] = deal_data_info($data[$k]['initial_price'], 2);
                $data[$k]['consult_price'] = deal_data_info($data[$k]['consult_price'], 2);
                $data[$k]['market_price'] = deal_data_info($data[$k]['market_price'], 2);
                $data[$k]['price_lower_offset'] = deal_data_info($data[$k]['price_lower_offset'], 2);
                $data[$k]['start_time'] = !empty($data[$k]['start_time']) ? date('Y/m/d H:i', $v['start_time']) : '';
                $data[$k]['end_time'] = !empty($data[$k]['end_time']) ? date('Y/m/d H:i', $v['end_time']) : '';
                unset($data[$k]['type']);
                $sourceList = House::$whereList['source_type'];
                foreach ($sourceList as $arr => $item)
                    $sourceList[$arr]['key'] == $data[$k]['source_type'] && $data[$k]['source_type'] = $sourceList[$arr]['value'];
            }
        } else {
            $data = [];
        }
        return $data;
    }

    /**
     * 验证参数
     * @param $params
     * @return bool
     */
    public static function checkParams(&$params) {
        date_default_timezone_set('PRC');
        if (!in_array($params['auction_status'], self::ASTATUS)) {
            Err::add('错误的拍卖状态', RespCode::PARAMS_ERR);
            return false;
        }
        if (!in_array($params['type'], self::ATYPE)) {
            Err::add('错误的拍卖阶段', RespCode::PARAMS_ERR);
            return false;
        }
        if (preg_match('/^(([1-9]{1}\d{0,9})|(0{1}))(\.\d{0,2})?$/', $params['initial_price']) == false) {
            Err::add('起拍价请输入1-9999999999的小数，最多两位小数', RespCode::PARAMS_ERR);
            return false;
        }
        if (mb_strlen(trim($params['source_url']), 'utf-8') > 250) {
            Err::add('来源地址长度超过250', RespCode::PARAMS_ERR);
            return false;
        }
        if (!empty($params['consult_price'])) {
            if (preg_match('/^(([1-9]{1}\d{0,9})|(0{1}))(\.\d{0,2})?$/', $params['consult_price']) == false) {
                Err::add('评估价请输入1-9999999999的小数，最多两位小数', RespCode::PARAMS_ERR);
                return false;
            }
        } else {
            $params['consult_price'] = 0;
        }
        if (!empty($params['market_price'])) {
            if (preg_match('/^(([1-9]{1}\d{0,9})|(0{1}))(\.\d{0,2})?$/', $params['market_price']) == false) {
                Err::add('市场价请输入1-9999999999的小数，最多两位小数', RespCode::PARAMS_ERR);
                return false;
            }
        } else {
            $params['market_price'] = 0;
        }
        if (empty($params['start_time']) || empty($params['end_time'])) {
            Err::add('请选择拍卖时间', RespCode::PARAMS_ERR);
            return false;
        }
        if (strtotime($params['start_time']) > strtotime($params['end_time'])) {
            Err::add('开始时间需小于结束时间', RespCode::PARAMS_ERR);
            return false;
        }
        if (strtotime($params['end_time']) < time()) {
            Err::add('结束时间需大于当前时间', RespCode::PARAMS_ERR);
            return false;
        }
        if (preg_match('/^[1-9]{1}\d{0,8}$/', $params['price_lower_offset']) == false) {
            Err::add('加价幅度请输入1-999999999的整数', RespCode::PARAMS_ERR);
            return false;
        }
        if (!empty($params['bond'])) {
            if (preg_match('/^[1-9]{1}\d{0,8}(.[0-9]{1,2})?$/', $params['bond']) == false) {
                Err::add('保证金请输入1-999999999的数字，最多两位小数', RespCode::PARAMS_ERR);
                return false;
            }
        }
        if (!empty(trim($params['court_name']))) {
            if (preg_match("/^[\x{4e00}-\x{9fa5}]{1,255}$/u", $params['court_name']) == false) {
                Err::add('处置单位请输入文字，字符限制255', RespCode::PARAMS_ERR);
                return false;
            }
        }
        if (!empty(trim($params['contact_tel']))) {
            if (mb_strlen(trim($params['contact_tel']), 'utf-8') > 30) {
                Err::add('联系电话长度限制30', RespCode::PARAMS_ERR);
                return false;
            }
        }
        if (!empty(trim($params['contact_name']))) {
            if (mb_strlen(trim($params['contact_name']), 'utf-8') > 255) {
                Err::add('联系人字符限制255', RespCode::PARAMS_ERR);
                return false;
            }
        }
        if (!empty($params['enroll_num'])) {
            if (!is_numeric($params['enroll_num']) || $params['enroll_num'] > 999999) {
                Err::add('报名人数请输入数字且不能超过999999', RespCode::PARAMS_ERR);
                return false;
            }
        }
        if (!empty($params['access_num'])) {
            if (!is_numeric($params['access_num']) || $params['access_num'] > 999999) {
                Err::add('围观人数请输入数字且不能超过999999', RespCode::PARAMS_ERR);
                return false;
            }
        }
        if (!empty($params['remind_num'])) {
            if (!is_numeric($params['remind_num']) || $params['remind_num'] > 999999) {
                Err::add('提醒人数请输入数字且不能超过999999', RespCode::PARAMS_ERR);
                return false;
            }
        }
        if (!empty($params['tail_money_date'])) {
            if (mb_strlen(trim($params['tail_money_date']), 'utf-8') > 30) {
                Err::add('尾款交付时间不能超过30位', RespCode::PARAMS_ERR);
                return false;
            }
        }
        if (mb_strlen(trim($params['source_id']), 'utf-8') > 20) {
            Err::add('来源id不能超过20位', RespCode::PARAMS_ERR);
            return false;
        }
        return true;
    }

    /**
     * 添加、编辑拍卖纪录
     * @param $params
     * @return bool
     */
    public static function editlog($params) {
        if (!self::checkParams($params)) {
            return false;
        }
        $params = price_arr_deal($params, 1);
        $getOne = self::getOne([['id', '=', $params['action_id']]], 'house_id');

        // 折扣比,保留两位小数
        $discount = -1;
        if (!empty($params['market_price'])) {
            // 当初始价 小于等于市场价时，才计算折扣
            if ($params['initial_price'] < $params['market_price']) {
                $discount = round($params['initial_price'] / $params['market_price'] * 10, 2);
                $discount < 1 && $discount = 0;
                $discount >= 10 && $discount = 10;
            }
        }

        $houseData = db('house')
            ->where('id', $getOne['house_id'])
            ->find();

        $data = [
            'house_id'           => $getOne['house_id'],
            'type'               => $params['type'],
            'start_time'         => strtotime($params['start_time']),
            'end_time'           => strtotime($params['end_time']),
            'initial_price'      => $params['initial_price'],
            'consult_price'      => $params['consult_price'],
            'discount'           => $discount,
            'market_price'       => $params['market_price'] ?? 0,
            'price_lower_offset' => $params['price_lower_offset'],
            'court_name'         => $params['court_name'] ?? '',
            'contact_name'       => $params['contact_name'] ?? '',
            'contact_tel'        => $params['contact_tel'] ?? '',
            'source_type'        => $params['source_type'],
            'source_id'          => $params['source_id'],
            'source_url'         => $params['source_url'],
            'auction_status'     => $params['auction_status'],
            'tail_money_date'    => $params['tail_money_date'] ?? '',
            'day_itime'          => strtotime(date('Y-m-d', time())),
            'month_itime'        => strtotime(date('Y-m', time())),
            'enroll_num'         => $params['enroll_num'] ?? 0,
            'access_num'         => $params['access_num'] ?? 0,
            'remind_num'         => $params['remind_num'] ?? 0,
            'bond'               => empty($params['bond']) ? 0 : $params['bond']
        ];

        if ($params['type'] == 4) {
            $data['pay_selloff'] = $data['initial_price'];
        }
        //添加拍卖
        if (empty($params['history_id'])) {
            $data['itime'] = time();
            $where[] = ['house_id', '=', $getOne['house_id']];
            $where[] = ['auction_status', 'in', [1, 2]];
            $has = self::getDatas($where, 'id', [], '');
            if ($has) {
                Err::add('有未完结状态，不能新增', RespCode::PARAMS_ERR);
                return false;
            }
            if (self::getDatas([['auction_status', '=', 3], ['house_id', '=', $getOne['house_id']]], 'id', [], '')) {
                Err::add('成交房源，不能新增', RespCode::PARAMS_ERR);
                return false;
            }

            //添加拍卖
            $insert_id = db('house_auction')
                ->insertGetId($data);

            //更新为拍卖的market_price
            $houseUpdate['market_price'] = $data['market_price'];

            if (isset($data['source_url'])) $houseUpdate['source_url'] = $data['source_url'];

            $houseUpdate['source_type'] = $data['source_type'];

            $houseUpdate['auction_id'] = $insert_id;

            //更新该房源对应拍卖id
            db('house')->where("id", $getOne['house_id'])->update($houseUpdate);

//            //状态改变后房源统计
//            $houseCount2 = new HouseCount2();
//            $houseCount2((string)$getOne['house_id'], (int)$params['auction_status']);

            return true;
        } else {
            //编辑
            $data['utime'] = time();
            $is_end = self::getOne([['id', '=', $params['history_id']]], 'auction_status');
            if (!in_array($is_end['auction_status'], [1, 2])) {
                Err::add('未完结状态不可编辑，不能编辑', RespCode::PARAMS_ERR);
                return false;
            }

            db('house_auction')->where('id', $params['history_id'])->update($data);

            $houseUpdate['market_price'] = $data['market_price'];

            if (isset($data['source_url'])) $houseUpdate['source_url'] = $data['source_url'];

            $houseUpdate['source_type'] = $data['source_type'];

            //更新房源的市场价
            db('house')->where('id', $getOne['house_id'])->update($houseUpdate);

//            //状态改变后房源统计
//            $houseCount2 = new HouseCount2();
//            $houseCount2((string)$getOne['house_id'], (int)$params['auction_status']);

            return true;
        }
    }

    /**
     * 是否存在待开始和进行中纪录
     * @param $params
     * @return bool
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    public static function is_add($params) {
        $getOne = self::getOne([['id', '=', $params['action_id']]], 'house_id');
        $map[] = ['house_id', '=', $getOne['house_id']];
        $map[] = ['auction_status', 'in', [1, 2]];
        if (db('house')->where('id', $getOne['house_id'])->value('deleted') == 1) {
            Err::add('房源不存在', RespCode::PARAMS_ERR);
            return false;
        }
        $data = self::getDatas($map, 'id', [], '');
        if ($data) {
            Err::add('有未完结状态，不能新增', RespCode::PARAMS_ERR);
            return false;
        }
        if (self::getDatas([['auction_status', '=', 3], ['house_id', '=', $getOne['house_id']]], 'id', [], '')) {
            Err::add('成交房源，不能新增', RespCode::PARAMS_ERR);
            return false;
        }
        return true;
    }

    /**
     * 筛选单条
     * @param $map
     * @param $column
     * @return array|PDOStatement|string|Model|null
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    public static function getOne($map, $column) {
        return $data = Db::name('house_auction')
            ->where($map)
            ->field($column)
            ->find();
    }

    /**
     * 筛选多条
     * @param $map
     * @param $column
     * @return array|PDOStatement|string|Collection
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    public static function getDatas($map, $column, $order, $orderRaw) {
        $data = Db::name('house_auction')
            ->where($map)
            ->field($column);
        if ($orderRaw) {
            $data = $data->orderRaw("field(id,{$orderRaw})");
        }
        $data = $data->order($order)
            ->select();
        return $data;
    }

    /**
     * 当前状态是否完结
     * @param $map
     * @param $column
     * @return bool
     */
    public static function is_end($map, $column) {
        $is_end = self::getOne($map, $column);
        if (!in_array($is_end['auction_status'], [1, 2])) {
            Err::add('完结状态不可编辑', RespCode::PARAMS_ERR);
            return false;
        } else {
            return true;
        }
    }

    /**
     * 处理时间
     * @param array $info
     * @return array
     */
    public static function dealTimeAndMoney(array $info) {
        $info['start_time'] = date('Y/m/d H:i', $info['start_time']);
        $info['end_time'] = date('Y/m/d H:i', $info['end_time']);
        $info['initial_price'] = deal_data_info($info['initial_price'], 2);
        $info['consult_price'] = deal_data_info($info['consult_price'], 2);
        $info['market_price'] = deal_data_info($info['market_price'], 2);
        $info['price_lower_offset'] = deal_data_info($info['price_lower_offset'], 2);
        $info['bond'] = deal_data_info($info['bond'], 2);
        return $info;
    }

}
